//
//  MessageViewController.swift
//  koolcar
//
//  Created by kuaimaxiansheng on 2023/9/21.
//

import UIKit
import MJRefresh

class MessageViewController: BaseViewController {
    var tableView: BaseTableView!
    var emptyView: LYEmptyView!
    var pageNumber = 1
    var dataArray = NSMutableArray()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = Theme.F5Color
        self.navBar.title = MMLocalizedString("message_station", comment: "站内讯息")
        self.initTableView()
        self.requestGetMassagesList(isMore: false)
    }
       
    func initTableView(){
        self.tableView = BaseTableView(frame: CGRect(x: 0, y: NavBarHight, width: kScreenWidth, height: kScreenHeight - NavBarHight), style: .plain)
        self.tableView.delegate = self
        self.tableView.dataSource = self
        self.tableView.rowHeight = UITableViewAutomaticDimension
        self.tableView.register(MessageTableViewCell.self, forCellReuseIdentifier: "MessageTableViewCell")
        self.tableView.estimatedRowHeight = 2
        self.view.addSubview(self.tableView)
        
        self.setUpNoData()
        self.addPullRefreash()
        self.addLoadMoreRefreash()
    }

    ///空视图
    func setUpNoData() {
        self.emptyView = LYEmptyView.emptyActionView(withImageStr: "icon_message_empty", titleStr: MMLocalizedString("no_data", comment: "暂无数据"), detailStr: "", btnTitleStr: "") {

        }
        emptyView.titleStr = ""
        emptyView?.subViewMargin = 28
        emptyView?.contentViewOffset = 0
        emptyView.isHidden = true
        self.tableView.ly_emptyView = self.emptyView
    }

    ///空视图
    func willShowEmptyView() {
        if self.dataArray.count == 0 {
            self.tableView.mj_footer?.isHidden = true
            self.emptyView.isHidden = false
            self.emptyView?.titleStr = MMLocalizedString("no_message", comment: "没有消息")
        }else{
            self.emptyView.isHidden = true
            self.emptyView?.titleStr = ""
        }
    }
    
    
    /*
     添加头部刷新
     */
    func addPullRefreash(){
        weak var weakSelf = self
        self.tableView.mj_header = MJRefreshNormalHeader.init(refreshingBlock: {
            weakSelf?.pageNumber = 1
            weakSelf?.requestGetMassagesList(isMore: false)
        })
    }
    
    //MARK: -  底部刷新
    func addLoadMoreRefreash(){
        weak var weakSelf = self
        self.tableView.mj_footer = ExtNoMoreRefreashFooterView.init(refreshingBlock: {
            weakSelf?.pageNumber = weakSelf!.pageNumber + 1
            weakSelf?.requestGetMassagesList(isMore: true)
        })
    }
    
    
    //MARK: - Request
    
    //站内讯息列表
    func requestGetMassagesList(isMore: Bool){
        if isMore {
            self.view.showLoadingHUDText()
        }
     
        let param = ["pageNumber": "\(self.pageNumber)","pageSize": "10"]
        XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.massagesList(param: param),objectType: MessageModel.self) { data in
            let resultObj = data as! MessageModel
            self.tableView.mj_header?.endRefreshing()
            self.tableView.mj_footer?.endRefreshing()
            self.view.handleLoading()
            if resultObj.code == "1" {
                if isMore == false{
                    self.dataArray.removeAllObjects()
                }
                self.dataArray.addObjects(from: resultObj.data?.content ?? [])
            }
            
            if self.dataArray.count < 10{
                self.tableView.mj_footer?.endRefreshingWithNoMoreData()
            }
            
            self.tableView.reloadData()
            self.willShowEmptyView()
        }error: { err in
            self.willShowEmptyView()
            self.tableView.mj_header?.endRefreshing()
            self.tableView.mj_footer?.endRefreshing()
            self.view.handleLoading()
            self.view.makeToast(message: err?.domain ?? MMLocalizedString("request_failed", comment: "请求失败，请稍候再试"))
        }
    }
    
    //站内讯息更新已读标识
    func requestMassagesUpdateFlag(massagesId: String){
        let param = ["massagesId": massagesId]
        XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.massagesUpdateFlag(param: param),objectType: CommondResModel.self) { data in
            let resultObj = data as! CommondResModel
            if resultObj.code == "1" {
                self.requestGetMassagesList(isMore: false)
            }
        }error: { err in
            self.view.makeToast(message: err?.domain ?? MMLocalizedString("request_failed", comment: "请求失败，请稍候再试"))
        }
    }
    
    
}

extension MessageViewController: UITableViewDelegate,UITableViewDataSource{
    func numberOfSections(in tableView: UITableView) -> Int {
        return self.dataArray.count
  
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
       
        return UITableViewAutomaticDimension
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "MessageTableViewCell", for: indexPath) as! MessageTableViewCell
        if self.dataArray.count > indexPath.section{
            let model = self.dataArray[indexPath.section] as! MessageListModel
            cell.setModel(model: model)
        }
       return cell
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
            return 10
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let headerView = UIView(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: 10))
          headerView.backgroundColor = .clear
        return headerView
    }
    
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let footerView = UIView(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: 0.01))
        footerView.backgroundColor = .clear
        return footerView
    }
    
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if self.dataArray.count > indexPath.section{
            let model = self.dataArray[indexPath.section] as! MessageListModel
            if model.status == 0{
                self.requestMassagesUpdateFlag(massagesId: "\(model.id ?? 0)")
            }
            let vc = MessageDetailViewController()
            vc.massagesId = "\(model.massagesId ?? 0)"
            self.navigationController?.pushViewController(vc, animated: true)
        }
    }
    
}
